# -*- coding: utf-8 -*-
from google.appengine.dist import use_library
use_library('django', '1.2')

import cgi, os
import logging

from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp, db
from google.appengine.api import xmpp, mail
from google.appengine.api.labs import taskqueue

from db import User

class Im(webapp.RequestHandler):
  def post(self):
	# get data
	try:
		logging.info("%s is here" % self.request.get('destin'))
		destin = User.all().filter('name =', self.request.get('destin')).get()
		if not destin:
			logging.debug("die. Reason: destin unknown")
			return
		sender = self.request.get('sender')
		subject = self.request.get('subject')
		chat_msg_send = ''
	except:
		logging.warning("die. Not able to gather information")
		return
	# try to send a message
	if destin.im:
		msg = u"%s vous a envoyé un message" % sender
		status_code = xmpp.send_message(destin.im.address, msg)
		chat_msg_send = (status_code != xmUser.NO_ERROR)
	else:
		status_code = "no im"
		chat_msg_send = False
	# fallback: mail
	if not chat_msg_send:
		logging.debug("fallback: email. Reason: %s" % status_code)
		alertMail = taskqueue.Task(url='/out/email',
								params={'destin':self.request.get('destin'),
									'sender': sender, 'subject': subject})
		alertMail.add('email')
	else:
		logging.debug('instant message sended')

class email(webapp.RequestHandler):
  def post(self):
	destin = self.request.get('destin')
	sender = self.request.get('sender')
	subject = self.request.get('subject')
	logging.debug("email to %s" % destin)
	adress = User.all().filter('name =', destin).get()
	  
	if mail.is_email_valid(adress.mail):
		logging.debug("email is valid")
		app_address = u"<hordes.mp@gmail.com>"
		title = u"[hmp] Nouveau message"
		body = u"%s vous a envoyé un message intitulé \"%s\"\n\nVous pouvez le consulter sur la messagerie.\n\n\n\
				--\nhttp://hordes-mp.appspot.com" % (sender,subject)

		mail.send_mail(app_address, adress.mail, title, body)

#

application = webapp.WSGIApplication([	('/out/email', email),
										('/out/im', Im),
									], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
		
